package com.common.widget;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import uk.co.senab.photoview.PhotoView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.RelativeLayout;

import com.common.allCommon.CommUtil;
import com.common.android.ui.gif.GifImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.product.android.ui.imageHolder.DownloadListener;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.EventBusException;

/**
 * 预览大图视图基类
 * 
 * <br>
 * Created 2014-6-12 下午1:46:20
 * 
 * @version
 * @author HuangYK
 * 
 * @see
 */
public abstract class PhotoPreviewBaseLayout extends RelativeLayout {

	/** 上下文 */
	protected Activity mActivity;

	/** 是否正在下载 */
	protected boolean mIsDownloading = false;

	/** 用于显示普通图片 */
	protected PhotoView mIvPicture;
	/** 用于显示GIF图片 */
	protected GifImageView mGifPicture;
	// /** 圆圈进度条布局 */
	// protected RelativeLayout rlProgress;
	// /** 圆圈进度条 */
	// protected CircleProgress cpProgress;
	/** 当前图片的位置，如果单张图片，直接设置-1，如果多张图片设置相应的position。 */
	protected int mPos;
	/** 是否显示进度条 */
	protected boolean mIsShow = true;
	/** 图片URL */
	protected String mUrl;
	/** 缩略图URL */
	protected String mThumbnail;
	/** 图片下载完成后的绝对路径。只有本地存在的时候才非空 */
	protected String mAbsPath = "";
	/** 图片是否是本地的 */
	protected boolean mIsLocalUrl = false;
	/** 显示图片需要的一些配置，比如图片所在的文件夹目录等 */
	protected DisplayImageOptions mDisplayImageOpt;
	/** 加载图片的控件 */
	private ImageLoader mImageLoader = ImageLoader.getInstance();

	/**
	 * 判断是否是GIF
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:30:29
	 * 
	 * @return
	 * @author : HuangYK
	 */
	public abstract boolean isGif();

	/**
	 * EventBus通知回调处理
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:30:38
	 * 
	 * @param obj
	 *            回调数据
	 * @author : HuangYK
	 */
	public abstract void mEventMainThread(DownloadProgress obj);

	/**
	 * 初始化xml布局
	 * 
	 * <br>
	 * Created 2014-6-12 下午1:56:57
	 * 
	 * @author : HuangYK
	 */
	protected abstract void initLayoutInflater();

	/**
	 * 初始化视图控件
	 * 
	 * <br>
	 * Created 2014-6-12 下午1:57:32
	 * 
	 * @author : HuangYK
	 */
	protected abstract void initView();

	/**
	 * 初始化视图操作事件
	 * 
	 * <br>
	 * Created 2014-6-12 下午1:57:44
	 * 
	 * @author : HuangYK
	 */
	protected abstract void initEvent();

	/**
	 * 创建实例
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:36:01
	 * 
	 * @param context
	 *            上下文
	 */
	public PhotoPreviewBaseLayout(Activity activity) {
		super(activity);
		mActivity = activity;
	}

	/**
	 * 监听下载进度回调
	 */
	public DownloadListener progressListener = new DownloadListener() {

		@Override
		public void success(String url) {
			EventBus.getDefault().post(new DownloadProgress(100, url));
		}

		@Override
		public void fail(String url) {
			EventBus.getDefault().post(new DownloadProgress(-1, url));
		}

		@Override
		public void showProgress(long totalSize, long downloadSize, String url) {
			if (0 == totalSize) {
				return;
			}
			long percentage = downloadSize * 100 / totalSize;
			EventBus.getDefault().post(
					new DownloadProgress((int) percentage, url));
		}

	};

	/**
	 * 图片下载监听回调
	 */
	public SimpleImageLoadingListener loadingListener = new SimpleImageLoadingListener() {

		/**
		 * 下载成功处理
		 * 
		 * <br>
		 * Created 2014-6-12 上午10:37:31
		 * 
		 * @param imageUri
		 *            图片URI
		 * @param view
		 *            视图
		 * @param loadedImage
		 *            已下载图片
		 * @author : HuangYK
		 */
		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			progressListener.success(imageUri);
			unRegisterEvent();
			mAbsPath = mImageLoader.getDiscCacheFileAbsPath(mDisplayImageOpt,
					mUrl);

			if (isGif() && checkIsGif(mAbsPath)) {
				// 如果是GIF图片，通过imageloader下载完成后，需要传递本地保存路径到gif的显示控件
				mIvPicture.setVisibility(View.GONE);
				if (mGifPicture != null) {
					mGifPicture.setVisibility(View.VISIBLE);
					try {
						mGifPicture.setGifImage(mAbsPath);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
			} else {
				mIvPicture.setVisibility(View.VISIBLE);
				mIvPicture.setImageBitmap(loadedImage);
				if (mGifPicture != null) {
					mGifPicture.setVisibility(View.GONE);
				}
			}

		}

		/**
		 * 下载终止处理
		 * 
		 * <br>
		 * Created 2014-6-12 上午10:41:36
		 * 
		 * @param imageUri
		 *            URI
		 * @param view
		 *            视图
		 * @author : HuangYK
		 */
		@Override
		public void onLoadingCancelled(String imageUri, View view) {
			progressListener.fail(imageUri);
			unRegisterEvent();
		}

		/**
		 * 下载失败处理
		 * 
		 * <br>
		 * Created 2014-6-12 上午10:41:49
		 * 
		 * @param imageUri
		 *            URI
		 * @param view
		 *            视图
		 * @param failReason
		 *            失败原因
		 * @author : HuangYK
		 */
		@Override
		public void onLoadingFailed(String imageUri, View view,
				FailReason failReason) {
			progressListener.fail(imageUri);
			unRegisterEvent();
		}

		/**
		 * 下载进度
		 * 
		 * <br>
		 * Created 2014-6-12 上午10:42:35
		 * 
		 * @param totalSize
		 *            总大小
		 * @param downloadSize
		 *            已下载大小
		 * @author : HuangYK
		 */
		@Override
		public void onLoadingProgress(long totalSize, long downloadSize) {
			progressListener.showProgress(totalSize, downloadSize, mUrl);
		}

		/**
		 * 开始下载
		 * 
		 * <br>
		 * Created 2014-6-12 上午10:42:49
		 * 
		 * @param imageUri
		 *            URI
		 * @param view
		 *            视图
		 * @author : HuangYK
		 */
		@Override
		public void onLoadingStarted(String imageUri, View view) {
			registerEvent();
			progressListener.showProgress(100, 0, imageUri);
		}

	};

	/**
	 * 注册EventBus
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:43:28
	 * 
	 * @author : HuangYK
	 */
	public void registerEvent() {
		try {
			EventBus.getDefault().register(this, DownloadProgress.class);
		} catch (EventBusException e) {

		}
	}

	/**
	 * 注销EventBus
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:43:36
	 * 
	 * @author : HuangYK
	 */
	public void unRegisterEvent() {
		EventBus.getDefault().unregister(this, DownloadProgress.class);
	}

	/**
	 * EventBus通知处理
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:43:42
	 * 
	 * @param obj
	 *            通知参数
	 * @author : HuangYK
	 */
	public void onEventMainThread(DownloadProgress obj) {
		mEventMainThread(obj);

		if (obj != null) {
			// DownloadProgress dp = (DownloadProgress) obj;
			if (obj.mUrl.equals(mUrl)) {
				if (obj.mPercentage == -1) {
					mIsDownloading = false;
				} else if (obj.mPercentage == 0) {
					mIsDownloading = true;
				} else if (obj.mPercentage >= 100) {
					mIsDownloading = false;
				} else {
					if (mIsShow) {
						mIsDownloading = true;
					} else {
						mIsDownloading = false;
					}
				}
			}
		}

		// if (rlProgress != null && cpProgress != null) {
		// if (obj instanceof DownloadProgress) {
		// DownloadProgress dp = (DownloadProgress) obj;
		// if (dp.mUrl.equals(url)) {
		// if (dp.mPercentage == -1) {
		// rlProgress.setVisibility(View.GONE);
		// } else if (dp.mPercentage == 0) {
		// rlProgress.setVisibility(View.VISIBLE);
		// cpProgress.setMainProgress(dp.mPercentage);
		// } else if (dp.mPercentage >= 100) {
		// rlProgress.setVisibility(View.GONE);
		//
		// } else {
		// if (isShow) {
		// rlProgress.setVisibility(View.VISIBLE);
		// } else {
		// rlProgress.setVisibility(View.GONE);
		// }
		// cpProgress.setMainProgress(dp.mPercentage);
		// }
		// }
		// }
		// }
	}

	/**
	 * 显示图片
	 * 
	 * <br>
	 * Created 2014-6-12 上午10:43:59
	 * 
	 * @param thumbnail
	 * @param url
	 * @param displayImageOpt
	 * @author : HuangYK
	 */
	public void showImage(String thumbnail, String url,
			DisplayImageOptions displayImageOpt) {
		// 专门用于显示图片，不论是GIF图片还是普通图片
		mThumbnail = thumbnail;
		mUrl = url;
		mDisplayImageOpt = displayImageOpt;
		mIvPicture.postInvalidate();

		if (!isGif()) {
			if (mIsLocalUrl) {
				// 如果是本地的普通图，必须加上"file://"字段才能被imageloader加载
				url = CommUtil.LOCAL_FILE_PREFIX + url;
				// 如果是本地的普通图，必须加上"file://"字段才能被imageloader加载
				thumbnail = CommUtil.LOCAL_FILE_PREFIX + thumbnail;
			}
			mIvPicture.setVisibility(View.VISIBLE);
			mIvPicture.setImageBitmap(ImageLoader.getInstance()
					.findCachedBitmapForImageUri(thumbnail));
			if (mGifPicture != null) {
				mGifPicture.setVisibility(View.GONE);
			}
			mImageLoader.displayImage(thumbnail, url, mIvPicture,
					displayImageOpt, loadingListener);
		} else {
			mIvPicture.setVisibility(View.GONE);
			if (mGifPicture != null)
				mGifPicture.setVisibility(View.VISIBLE);
			if (mIsLocalUrl) {
				try {
					if (checkIsGif(url)) {
						// 确实是GIF图片
						if (mGifPicture != null)
							mGifPicture.setGifImage(url);
					} else {
						// 扩展名是GIF,实际上不是GIF
						// 如果是本地的普通图，必须加上"file://"字段才能被imageloader加载
						url = CommUtil.LOCAL_FILE_PREFIX + url;
						// 如果是本地的普通图，必须加上"file://"字段才能被imageloader加载
						thumbnail = CommUtil.LOCAL_FILE_PREFIX + thumbnail;
						mImageLoader.displayImage(thumbnail, url, mIvPicture,
								displayImageOpt, loadingListener);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			} else {
				Bitmap bmp = mImageLoader
						.findCachedBitmapForImageUri(thumbnail);
				if (bmp != null && mGifPicture != null) {
					mGifPicture.setImageBitmap(bmp);
				}
				ImageLoader.getInstance().loadImage(mGifPicture, url,
						displayImageOpt, loadingListener);
			}

		}
	}

	/**
	 * 下载通知结构体
	 * 
	 * <br>
	 * Created 2014-6-11 下午7:30:09
	 * 
	 * @version PhotoPreviewBaseLayout
	 * @author HuangYK
	 * 
	 * @see
	 */
	public static class DownloadProgress {
		public int mPercentage;
		public String mUrl;

		public DownloadProgress(int percentage, String url) {
			mPercentage = percentage;
			mUrl = url;
		}
	}

	/**
	 * 根据本地文件判断是否GIF图片.
	 * 
	 * <br>
	 * Created 2014-6-11 下午7:29:42
	 * 
	 * @param path
	 *            图片的路径
	 * @return true：是gif，false：不是gif
	 * @author : HuangYK
	 */
	private boolean checkIsGif(String path) {
		File file = new File(path);
		if (file == null || !file.exists()) {
			return false;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			String id = "";
			for (int i = 0; i < 6; i++) {
				id += (char) is.read();
			}
			if (id.toLowerCase().startsWith("gif")) {
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * 判断当前是否正在下载
	 * 
	 * <br>
	 * Created 2014-6-11 下午7:28:54
	 * 
	 * @return true：正在下载，false：没有在下载
	 * @author : HuangYK
	 */
	public boolean isDownloading() {
		return mIsDownloading;
	}

	/**
	 * 停止gif
	 * 
	 * <br>
	 * Created 2014-6-12 下午4:29:49
	 * 
	 * @author : HuangYK
	 */
	public void quitGif() {
		mGifPicture.quit();
	}
	
	/**
	 * 停止下载
	 * 
	 * <br>Created 2014-7-18 下午4:28:26
	 * @author        :  HuangYK
	 */
	public void stopDownload(){
		if(isGif()){
			mImageLoader.cancelDisplayTask(mGifPicture);
		}else{
			mImageLoader.cancelDisplayTask(mIvPicture);
		}
	}
	
	/**
	 * 回收资源
	 * 
	 * <br>
	 * Created 2014-6-12 下午2:27:43
	 * 
	 * @author : HuangYK
	 */
	public void doDestroy() {
		quitGif();
		stopDownload();
		unRegisterEvent();
		mGifPicture.recycle();
	}

}
